const { ParamInvalidErr } = require('../../response/code')
const queryParseInt = (ctx, fields) => {
  if (ctx.request && ctx.request.query) {
    let keys = Object.keys(ctx.request.query)
    keys.forEach((key) => {
      if (fields.includes(key.toLocaleLowerCase())) {
        ctx.request.query[key] = parseInt(ctx.request.query[key])
      }
    })
  }
}
const validator = (rules) => {
  return async (ctx, next) => {
    try {
      // 转为整型
      queryParseInt(ctx, ['id', 'pageno', 'pagesize'])
      ctx.verifyParams(rules)
    } catch (err) {
      // 转为自定义错误,由errHandler统一处理
      ParamInvalidErr.data = err.errors || err.message
      return ctx.app.emit('error', ParamInvalidErr, ctx)
    }
    await next()
  }
}

module.exports = {
  validator,
}
